/*	Bulk File Renamer v1.0
	By DreamVB
	Usage rename.exe c:\work\*.doc .txt
*/

#include <iostream>
#include <Windows.h>

using namespace std;
using std::cout;
using std::endl;

int ChrPos(char *s, char ch){
	int idx = -1;
	int x = 0;

	//Find the last backslash in lzCmd
	for (x = 0; x < strlen(s); x++){
		if (s[x] == ch){
			idx = x;
		}
	}
	return idx;
}

int main(int argc, char *argv[]){
	HANDLE f = 0;
	WIN32_FIND_DATAA wfd;

	char lzPath[MAX_PATH];
	char lzCmd[MAX_PATH];
	char OrgFile[MAX_PATH];
	char NewFile[MAX_PATH];
	char fExtension[30];
	int pos = -1;
	int x = 0;

	//Check argv
	if (argc != 3){
		cout << "Usage: <Folder> <FileType>" << endl;
		exit(1);
	}

	//The two lines below copy the filename and file type form argv
	strcpy(lzCmd, argv[1]);
	strcpy(fExtension, argv[2]);
	strcpy(lzPath, lzCmd);

	//Find the last backslash in lzPath
	pos = ChrPos(lzPath, '\\');

	if (pos != -1){
		//Terminate string
		lzPath[pos + 1] = '\0';
		//Reset pos
		pos = -1;
	}

	//Find first file.
	f = FindFirstFileA(lzCmd, &wfd);

	//Check for inaild path.
	if (f == INVALID_HANDLE_VALUE){
		cout << "Folder or files not found." << endl << lzPath << endl;
		exit(1);
	}

	//Gets the list of files
	do{
		if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY){
			//Left for folders
		}
		else{
			//Build path and filename
			strcpy(OrgFile, lzPath);
			strcat(OrgFile, wfd.cFileName);
			//Set new filename
			strcpy(NewFile, OrgFile);
			//Remove file type from NewFile
			pos = ChrPos(NewFile, '.');

			//Append new file type to NewFile
			if (pos != -1){
				//Terminate string
				NewFile[pos] = '\0';
				//Append extension to new file
				strcat(NewFile, fExtension);
				//Rename the file
				if (rename(OrgFile, NewFile) != 0){
					//Output error
					cout << "IO/Error, Cannot rename file." <<
						endl << NewFile << endl;
				}
			} 
		}
	} while (FindNextFileA(f, &wfd) != false);

	//Close file
	FindClose(f);

	//Clear up.
	memset(lzCmd, 0, sizeof(lzCmd));
	memset(lzPath, 0, sizeof(lzPath));
	memset(OrgFile, 0, sizeof(OrgFile));
	memset(NewFile, 0, sizeof(NewFile));
	memset(fExtension, 0, sizeof(fExtension));

	return EXIT_SUCCESS;
}